import argparse
import os
import sys
import subprocess
import yaml
from yaml import FullLoader

sys.path.append('..')

from src.parser.md_parser import md2html
import time

from src.provider.docx_processor import DocxProcessor

config: dict = {
    "version": "0.1.0"
}

def resource_path(relative_path):
    if getattr(sys, 'frozen', False):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

def convert_markdown_to_docx(input_file, output_file, style_file):
    try:
        subprocess.run([
            "pandoc",
            "-o", output_file,
            "-f", "markdown+tex_math_single_backslash+tex_math_dollars",
            "-t", "docx",
            "--mathjax",
            "--wrap=none",
            "-s",
            "--reference-doc=" + style_file,
            "--pdf-engine=xelatex",
            "--resource-path=.:src:images",
            input_file
        ], check=True)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error: {e}")
        return False

if __name__ == '__main__':
    if len(sys.argv) == 1:
        sys.argv.append("-h")

    parser = argparse.ArgumentParser(description="markdocx - %s" % config["version"])
    parser.add_argument('input', help="Markdown file path")
    parser.add_argument('-o', '--output', help="Optional. Path to save docx file")
    parser.add_argument('-s', '--style',
                        help="Optional. YAML file with style configuration")
    parser.add_argument('-a', action="store_true",
                        help="Optional. Automatically open docx file when finished converting")
    args = parser.parse_args()
    docx_path = args.output if args.output is not None else args.input + ".docx"

    start_time = time.time()

    if not args.style:
        args.style = resource_path(os.path.join("config", "default_style.yaml"))

    with open(args.style, "r", encoding="utf-8") as file:
        conf = yaml.load(file, FullLoader)

    # 使用Pandoc直接转换Markdown到DOCX
    if convert_markdown_to_docx(args.input, docx_path, args.style):
        done_time = time.time()
        print("[SUCCESS] Convert finished in:", "%.4f" % (done_time - start_time), "sec(s).")
        print("[SUCCESS] Docx saved to:", os.path.abspath(docx_path))

        if args.a:
            os.system(f"open {os.path.abspath(docx_path)}")
    else:
        print("[ERROR] Conversion failed.")
